<script setup lang='ts'>
import { ApiMemberThirdAuthUrl } from '~/apis'
defineOptions({
  name: 'AppThirdLogin',
})

// 1:FB, 2:Google, 3:Twitch, 4:Line
enum AuthTypes {
  'fb' = 1,
  'google' = 2,
  'twitch' = 3,
  'line' = 4,
}

type AuthTypesKeys = keyof typeof AuthTypes

const { VITE_SOCKET_PREFIX } = getEnv()

const { t } = useI18n()
const appStore = useAppStore()
const brandStore = useBrandStore()
const { brandThird } = storeToRefs(brandStore)

const thirdAuth = computed(() => {
  const arr = []// 'fb', 'google', 'line', 'twitch'
  if (brandThird.value) {
    if (brandThird.value.FaceBook && +brandThird.value.FaceBook.state === 1)
      arr.push('fb')
    if (brandThird.value.Google && +brandThird.value.Google.state === 1)
      arr.push('google')
    if (brandThird.value.Twitch && +brandThird.value.Twitch.state === 1)
      arr.push('twitch')
    if (brandThird.value.Line && +brandThird.value.Line.state === 1)
      arr.push('line')
  }
  return arr
})

const ty = ref()
const state = ref(Math.random().toString(36).slice(-10))
const gWin = ref()

const topic = computed(() => `${VITE_SOCKET_PREFIX}/auth/${state.value}`)

const { run: runGetAuthUrl, loading: getAuthUrlLoading } = useRequest(ApiMemberThirdAuthUrl, {
  onSuccess: (data) => {
    setTimeout(() => {
      data && gWin.value?.location.replace(data)
    }, 0)
  },
})

async function goAuth(type: AuthTypesKeys) {
  if (gWin.value)
    gWin.value.close()

  gWin.value = window.open('', '_blank', 'popup=yes,width=600,height=600')
  ty.value = AuthTypes[type]
  runGetAuthUrl({ state: state.value, type, device_number: await application.getDeviceNumber() })
}

function dealMsg(data: any) {
  console.error('refreshAuthBus', data)
  // closeDialog()
  if (data) {
    if (data.action === 'register') {
      setTimeout(() => {
        // openThirdAuthFormDialog({ data: data.extra_data, ty: ty.value })
        const { id , email, name} = data.extra
        i18nNavigateTo({path:'/login/third',query:{e:email,i:id,name:name,ty:ty.value}})
      }, 0)
    }

    else if (data.action === 'success') {
      appStore.setToken(data.extra_data)
      message.success( `${t('tip_pop_up_reg_success_title')} ${data.member_name ?? '--'}!`)
    }

    else if (data.action === 'error') {
      message.error(data.extra_data )
    }
  }
  setTimeout(() => {
    gWin.value?.close()
  }, 1500)
}

onMounted(() => {
  socketClient.addSubscribe(topic.value, { callback: thirdAuthCallback })
  appEventBus.on(EventBusNames.REFRESH_AUTH_BUS, dealMsg)
})

onBeforeUnmount(() => {
  socketClient.removeSubscribe(topic.value)
  appEventBus.off(EventBusNames.REFRESH_AUTH_BUS, dealMsg)
})

await application.allSettled(
  [brandStore.refreshAsyncBrandBaseDetail()],
)
</script>

<template>
  <div v-if="thirdAuth.length" class="app-bottom">
    <div class="app-bottom-divider">
      <BaseDivider title-placement="center" size="1"
        style="--tg-text-lightgrey: #B3BEC1;--tg-base-divider-bg-color: rgba(228, 234, 240, 0.10);">
        <span class="text-[0.75rem]">{{ $t('direct_login') }}</span>
      </BaseDivider>
    </div>
    <div class="app-bottom-icon"
      :style="{ 'grid-template-columns': thirdAuth.length === 4 ? 'repeat(4,1fr)' : `repeat(${thirdAuth.length},25%)` }">
      <BaseButton v-if="thirdAuth.includes('fb')" :disabled="getAuthUrlLoading" type="none" class="item-svg third-btn"
        size="xs" @click="goAuth('fb')">
        <BaseIcon class="text-[1.5rem]" name="uni-fb" />
      </BaseButton>
      <BaseButton v-if="thirdAuth.includes('google')" :disabled="getAuthUrlLoading" type="none"
        class="item-svg third-btn" size="xs" @click="goAuth('google')">
        <BaseIcon class="text-[1.5rem]" name="uni-google" />
      </BaseButton>
      <BaseButton v-if="thirdAuth.includes('line')" :disabled="getAuthUrlLoading" type="none" class="item-svg third-btn"
        size="xs" @click="goAuth('line')">
        <BaseIcon class="text-[1.5rem]" name="uni-line" />
      </BaseButton>
      <BaseButton v-if="thirdAuth.includes('twitch')" :disabled="getAuthUrlLoading" type="none"
        class="item-svg third-btn" size="xs" @click="goAuth('twitch')">
        <BaseIcon class="text-[1.5rem]" name="uni-twitch" />
      </BaseButton>
    </div>
  </div>
</template>

<style lang='scss' scoped>
.app-bottom {
  font-size: var(--tg-font-size-default);
  display: grid;
  grid-template-columns: repeat(1, minmax(0, 1fr));
  row-gap: 0.75rem;
  margin-top: 1.5rem;

  &-divider {
    width: 100%;
    margin: 0 auto;

    span {
      color: var(--tg-text-lightgrey);
      height: 1.25rem;
      line-height: 1.25rem;
      display: inline-block;
    }
  }

  &-icon {
    gap: 0.25rem;
    width: 100%;
    display: grid;
    // grid-template-columns: repeat(4,1fr);
    grid-auto-rows: auto;
    justify-content: center;

    .item-svg {
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 0.25rem;
      border: 1px solid #3A4142;
      height: 2.5rem;
    }
  }
}
</style>
